﻿using Loki.Commands;
using Loki.IoC;
using Loki.Utils;
using NUnit.Framework;

namespace Loki.Core.Test
{
    [TestFixture]
    public class CommandBaseTest : AssertionHelper
    {
        public ICommand Command1 = null;
        public ICommand Command2 = null;

        public ICommandComponent Service = null;

        private IObjectContext context;

        [SetUp]
        public void SetUp()
        {
            context = Toolkit.IoC.CreateContext("TestContext");
            Service = context.Get<ICommandComponent>();
            Command1 = Service.CreateCommand("Command1");
            Command2 = Service.CreateCommand();
        }

        [Test]
        public void TestExecute1WithRegisteredHandler()
        {
            bool executed = false;
            ICommandHandler handler = LokiCommandHandler.Create(
                (obj, args) => args.CanExecute |= args.Command.Name == Command1.Name,
                delegate(object obj, CommandEventArgs args) { executed = true; }
                );

            Service.AddHandler(Command1, handler);

            Command1.Execute(null);

            Expect(
                executed,
                Is.True
                );
        }

        [Test]
        public void TestExecute1WithRemovedHandler()
        {
            bool executed = false;
            ICommandHandler handler = LokiCommandHandler.Create(
                (obj, args) => args.CanExecute |= args.Command.Name == Command1.Name,
                delegate(object obj, CommandEventArgs args) { executed = true; }
                );

            Service.AddHandler(Command1, handler);

            Service.RemoveHandler(Command1, handler);

            Command1.Execute(null);

            Expect(
                executed,
                Is.False
                );
        }

        [Test]
        public void TestExecute2WithRegisteredHandler()
        {
            bool executed = false;
            ICommandHandler handler = LokiCommandHandler.Create(
                (obj, args) => args.CanExecute |= args.Command.Name == Command1.Name,
                delegate(object obj, CommandEventArgs args) { executed = true; }
                );

            Service.AddHandler(Command2, handler);

            Command2.Execute(null);

            Expect(
                executed,
                Is.False
                );
        }

        [TearDown]
        public void TearDown()
        {
            Toolkit.IoC.DropContext(context);
        }
    }
}